<template>
    <div class="video-image-form-container">
        <!-- 页面头部 -->
        <div class="page-header">
            <div class="header-content">
                <div class="header-left">
                    <h2>{{ isEdit ? '编辑内容' : '新增内容' }}</h2>
                </div>
                <div class="header-right">
                    <el-button @click="handleCancel">
                        <el-icon><ArrowLeft /></el-icon>
                        返回
                    </el-button>
                </div>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form-content">
            <el-card shadow="never" class="form-card">
                <el-form
                    ref="videoImageFormRef"
                    :model="formData"
                    :rules="formRules"
                    label-width="120px"
                    class="video-image-form"
                >
                    <!-- 中英文 -->
                    <el-form-item label="中英文:" prop="language">
                        <el-select v-model="formData.language" placeholder="请选择" style="width: 200px">
                            <el-option label="中文" value="zh" />
                            <el-option label="英文" value="en" />
                        </el-select>
                    </el-form-item>

                    <!-- 标题 -->
                    <el-form-item label="标题:" prop="title">
                        <el-input
                            v-model="formData.title"
                            placeholder="输入服务标题"
                            style="width: 300px"
                        />
                    </el-form-item>

                    <!-- 文章分类 -->
                    <el-form-item label="文章分类:" prop="articleCategory">
                        <el-select v-model="formData.articleCategory" placeholder="请选择..." style="width: 200px">
                            <el-option label="视频分类" value="video" />
                            <el-option label="图文分类" value="image" />
                        </el-select>
                    </el-form-item>

                    <!-- 话题 -->
                    <el-form-item label="话题:" prop="topic">
                        <el-select v-model="formData.topic" placeholder="请选择..." style="width: 200px">
                            <el-option label="情感话题" value="emotion" />
                            <el-option label="风水话题" value="fengshui" />
                            <el-option label="健康话题" value="health" />
                            <el-option label="生活话题" value="life" />
                        </el-select>
                    </el-form-item>

                    <!-- 文章内容 -->
                    <el-form-item label="文章内容:" prop="content">
                        <div class="rich-editor-container">
                            <Toolbar
                                style="border-bottom: 1px solid #ccc"
                                :editor="editorRef"
                                :defaultConfig="toolbarConfig"
                                :mode="mode"
                            />
                            <Editor
                                style="height: 300px; overflow-y: hidden;"
                                v-model="formData.content"
                                :defaultConfig="editorConfig"
                                :mode="mode"
                                @onCreated="handleCreated"
                            />
                        </div>
                    </el-form-item>

                    <!-- 操作按钮 -->
                    <el-form-item>
                        <div class="form-actions">
                            <el-button @click="handleCancel">取消</el-button>
                            <el-button type="primary" @click="handleSubmit">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onBeforeUnmount, shallowRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ArrowLeft } from '@element-plus/icons-vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';

const route = useRoute();
const router = useRouter();

const id = route.params.id as string;
const isEdit = computed(() => !!id);

// 编辑器相关
const editorRef = shallowRef();
const mode = 'default';

// 编辑器配置
const toolbarConfig = {
    toolbarKeys: [
        'headerSelect',
        'blockquote',
        '|',
        'bold',
        'underline',
        'italic',
        {
            key: 'group-more-style',
            title: '更多样式',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M204.8 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M505.6 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path><path d="M806.4 505.6m-76.8 0a76.8 76.8 0 1 0 153.6 0 76.8 76.8 0 1 0-153.6 0Z"></path></svg>',
            menuKeys: ['through', 'code', 'sup', 'sub', 'clearStyle']
        },
        'color',
        'bgColor',
        '|',
        'fontSize',
        'fontFamily',
        'lineHeight',
        '|',
        'bulletedList',
        'numberedList',
        'todo',
        {
            key: 'group-justify',
            title: '对齐',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z"></path></svg>',
            menuKeys: ['justifyLeft', 'justifyCenter', 'justifyRight', 'justifyJustify']
        },
        {
            key: 'group-indent',
            title: '缩进',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M0 64h1024v128H0z m384 192h640v128H384z m0 192h640v128H384z m0 192h640v128H384zM0 832h1024v128H0z m0-128V320l256 192z"></path></svg>',
            menuKeys: ['indent', 'delIndent']
        },
        '|',
        'emotion',
        'insertLink',
        {
            key: 'group-image',
            title: '图片',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M959.877 128l0.123 0.123v767.775l-0.123 0.122H64.102l-0.122-0.122V128.123l0.122-0.123h895.775zM960 64H64C28.795 64 0 92.795 0 128v768c0 35.205 28.795 64 64 64h896c35.205 0 64-28.795 64-64V128c0-35.205-28.795-64-64-64zM832 288.01c0 53.023-42.988 96.01-96.01 96.01s-96.01-42.987-96.01-96.01S682.967 192 735.99 192 832 234.988 832 288.01zM896 832H128V704l224.01-168 96.01 72.01 224.01-168L896 640v192z"></path></svg>',
            menuKeys: ['insertImage', 'uploadImage']
        },
        {
            key: 'group-video',
            title: '视频',
            iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M981.184 160.096C837.568 139.456 678.848 128 512 128S186.432 139.456 42.816 160.096C15.296 267.808 0 386.848 0 512s15.264 244.16 42.816 351.904C186.464 884.544 345.152 896 512 896s325.568-11.456 469.184-32.096C1008.704 756.192 1024 637.152 1024 512s-15.264-244.16-42.816-351.904zM384 704V320l320 192-320 192z"></path></svg>',
            menuKeys: ['insertVideo', 'uploadVideo']
        },
        'insertTable',
        'codeBlock',
        'divider',
        '|',
        'undo',
        'redo',
        '|',
        'fullScreen'
    ]
};

const editorConfig = {
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: '/api/upload',
            fieldName: 'file',
            maxFileSize: 10 * 1024 * 1024,
            allowedFileTypes: ['image/*'],
            headers: {
                Accept: 'text/x-json',
                otherKey: 'xxx'
            },
            meta: {
                token: 'xxx',
                otherKey: 'yyy'
            },
            metaWithUrl: false,
            withCredentials: false,
            timeout: 5 * 1000,
            onBeforeUpload(file: File) {
                console.log('onBeforeUpload', file);
                return file;
            },
            onProgress(progress: number) {
                console.log('onProgress', progress);
            },
            onSuccess(file: File, res: any) {
                console.log('onSuccess', file, res);
            },
            onFailed(file: File, res: any) {
                console.log('onFailed', file, res);
            },
            onError(file: File, err: any, res: any) {
                console.log('onError', file, err, res);
            }
        }
    }
};

// 表单引用
const videoImageFormRef = ref();

// 表单数据
const formData = reactive({
    language: '',
    title: '',
    articleCategory: '',
    topic: '',
    content: ''
});

// 表单验证规则
const formRules = {
    language: [
        { required: true, message: '请选择中英文', trigger: 'change' }
    ],
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 2, max: 20, message: '标题长度在2-20个字符', trigger: 'blur' }
    ],
    articleCategory: [
        { required: true, message: '请选择文章分类', trigger: 'change' }
    ],
    topic: [
        { required: true, message: '请选择话题', trigger: 'change' }
    ],
    content: [
        { required: true, message: '请输入文章内容', trigger: 'blur' }
    ]
};

// 编辑器创建
const handleCreated = (editor: any) => {
    editorRef.value = editor;
};

// 提交表单
const handleSubmit = async () => {
    if (!videoImageFormRef.value) return;
    
    try {
        await videoImageFormRef.value.validate();
        
        ElMessageBox.confirm(
            `确定要${isEdit.value ? '更新' : '保存'}此内容吗？`,
            '确认操作',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'success',
            }
        ).then(() => {
            ElMessage.success(`${isEdit.value ? '更新' : '保存'}成功`);
            router.push('/video-image-list');
        }).catch(() => {
            ElMessage.info('已取消操作');
        });
    } catch (error) {
        ElMessage.error('请检查表单信息');
    }
};

// 取消操作
const handleCancel = () => {
    router.push('/video-image-list');
};

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        // 编辑模式：加载现有数据
        loadContentData(id);
    }
});

// 页面销毁
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;
    editor.destroy();
});

// 加载内容数据
const loadContentData = (contentId: string) => {
    // 模拟加载数据
    console.log('加载内容数据，ID:', contentId);
    // 这里可以调用API加载数据
    // 示例数据
    Object.assign(formData, {
        language: 'zh',
        title: '图文标题',
        articleCategory: 'video',
        topic: 'emotion',
        content: '趣闻1947年,时装设计师 Elsa Schiaparelli 将"艳粉色"引入西方时尚圈。桃色可以营造亲密氛围,减少攻击性和敌意。由于听说粉色有一种镇定效果,有些球队会把客队的休息室漆成粉色。对于粉色的研究发现,男性举重运动员在粉色房间内似乎感到力不从心,而女性举重运动员面对这种颜色反而会有变强的倾向。糕点从粉色盒子里取出或盛在粉色盘子里时,尝起来会更美味(这种情况仅适用于甜点),因为粉色令我们渴望糖份。'
    });
};
</script>

<style scoped>
.video-image-form-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.page-header {
    border-radius: 8px;
    margin-bottom: 20px;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.header-left h2 {
    margin: 0;
    color: #333;
    font-size: 24px;
}

.form-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.form-card {
    border-radius: 8px;
}

.video-image-form {
    padding: 30px;
}

.form-hint {
    color: #f56c6c;
    font-size: 12px;
    margin-top: 4px;
}

.form-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    margin-top: 20px;
}

.rich-editor-container {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .video-image-form-container {
        padding: 10px;
    }
    
    .header-content {
        flex-direction: column;
        gap: 16px;
        align-items: flex-start;
    }
    
    .video-image-form {
        padding: 20px;
    }
    
    .form-actions {
        justify-content: center;
    }
}
</style>
